package cn.org.gupao.mini.mvc;

import cn.org.gupao.mini.mvc.annotation.*;
import cn.org.gupao.mini.mvc.bean.Constant;
import cn.org.gupao.mini.mvc.bean.Container;
import cn.org.gupao.mini.mvc.bean.Handler;
import cn.org.gupao.mini.mvc.bean.PropertiesFactory;
import cn.org.gupao.mini.mvc.utils.StringUtils;
import cn.org.gupao.mini.mvc.utils.TypeConvertUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyDispatcherServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write(Constant.ERROR);
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        Handler handler = getHandler(req);
        if (handler==null) {
            resp.getWriter().write(Constant.NOT_FOUND);
            return;
        }
        //获取参数列表
        Object[] paramValues = getParamValues(handler,req.getParameterMap(),req,resp);

        //执行真正的方法
        Object returnValue = handler.getMethod().invoke(handler.getController(),paramValues);
        if(returnValue == null || returnValue instanceof Void){ return; }
        resp.getWriter().write(returnValue.toString());
    }

    private Object[] getParamValues(Handler handler, Map<String, String[]> paramMap, HttpServletRequest req, HttpServletResponse resp) {
        Class<?>[] paramTypes = handler.getMethod().getParameterTypes();

        Map<String,Integer> paramIndexMapping = getParamIndexMapping(handler.getMethod());
        Object[] paramValues = new Object[paramTypes.length];

        for(Map.Entry<String,String[]> param:paramMap.entrySet()){
            if(!paramIndexMapping.containsKey(param.getKey())) continue;

            int index = paramIndexMapping.get(param.getKey());
            String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]","")
                    .replaceAll("\\s",",");
            paramValues[index] = TypeConvertUtils.convert(paramTypes[index],value);
        }

        if(paramIndexMapping.containsKey(HttpServletRequest.class.getName())) {
            int reqIndex = paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[reqIndex] = req;
        }

        if(paramIndexMapping.containsKey(HttpServletResponse.class.getName())) {
            int respIndex = paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[respIndex] = resp;
        }
        return paramValues;
    }

    private Map<String,Integer> getParamIndexMapping(Method method){
        Map<String,Integer> paramIndexMapping = new HashMap<>();
        //提取方法中加了注解的参数
        //把方法上的注解拿到，得到的是一个二维数组
        //因为一个参数可以有多个注解，而一个方法又有多个参数
        Annotation[] [] pa = method.getParameterAnnotations();
        for (int i = 0; i < pa.length ; i ++) {
            for(Annotation a : pa[i]){
                if(a instanceof MYRequestParam){
                    String paramName = ((MYRequestParam) a).value();
                    if(!"".equals(paramName.trim())){
                        paramIndexMapping.put(paramName, i);
                    }
                }
            }
        }

        //提取方法中的request和response参数
        Class<?> [] paramsTypes = method.getParameterTypes();
        for (int i = 0; i < paramsTypes.length ; i ++) {
            Class<?> type = paramsTypes[i];
            if(type == HttpServletRequest.class ||
                    type == HttpServletResponse.class){
                paramIndexMapping.put(type.getName(),i);
            }
        }
        return paramIndexMapping;
    }

    private Handler getHandler(HttpServletRequest req) {
        if (Container.handlerMapping.isEmpty()) return null;
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath,"").replaceAll("/+","/");

        for (Handler handler:Container.handlerMapping){
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()) continue;
            return handler;
        }
        return null;
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        //加载配置文件
        doLoadConfig(servletConfig.getInitParameter("contextConfigLocation"));
        ///扫描所有的类
        doScanner(PropertiesFactory.getInstance().getProperty(Constant.SCAN_PACKAGE));
        //实例化所有的类并放入容器中
        doInstance();
        //依赖注入
        doAutowired();
        //初始化handlerMapping
        initHandlerMapping();
        System.out.println("init complete");
    }

    private void initHandlerMapping() {
        if(Container.ioc.isEmpty()) return;

        String baseUrl = "";
        for (Map.Entry<String,Object> entry:Container.ioc.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(MYController.class)) continue;

            if(clazz.isAnnotationPresent(MYRequestMapping.class)){
                baseUrl = clazz.getAnnotation(MYRequestMapping.class).value();
            }

            for (Method method:clazz.getMethods()){
                 if(!method.isAnnotationPresent(MYRequestMapping.class)) continue;
                 baseUrl = "/" + baseUrl + "/" + method.getAnnotation(MYRequestMapping.class).value();
                 Container.handlerMapping.add(new Handler(Pattern.compile(baseUrl.replaceAll("/+","/").replaceAll("\\*",".*")),entry.getValue(),method));
            }
        }
    }

    /**
     * 对ioc容器中的所有实例进行依赖注入
     */
    private void doAutowired() {
        if (Container.ioc.isEmpty()) return;

        Field[] fields;
        String beanName;
        for (Map.Entry<String,Object> entry:Container.ioc.entrySet()){
            fields = entry.getValue().getClass().getDeclaredFields();
            if(fields==null || fields.length==0){continue;}
            for(Field field:fields){
                if (!field.isAnnotationPresent(MYAutowired.class)) continue;
                beanName = field.getAnnotation(MYAutowired.class).value();
                if(!"".equals(beanName.trim())){
                    beanName = field.getType().getName();
                }
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(),Container.ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 实例化所有bean并放入ioc容器中
     */
    private void doInstance() {
        if (Container.classNames.isEmpty()) return;
        try {
            String beanName = null;
            for (String className:Container.classNames){
                 Class<?> clazz = Class.forName(className);
                 if(clazz.isAnnotationPresent(MYController.class)){
                     beanName = StringUtils.toLowerFirstCase(clazz.getSimpleName());
                 }else if(clazz.isAnnotationPresent(MYService.class)){
                        beanName = clazz.getAnnotation(MYService.class).value();
                        if("".equals(beanName.trim())){
                            beanName = clazz.getSimpleName();
                        }
                        doInstanceInterface(clazz);
                 }else{
                     continue;
                 }
                Container.ioc.put(beanName,clazz.newInstance());
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    /**
     * 根据接口类型注入
     * @param clazz
     * @throws Exception
     */
    private void doInstanceInterface(Class<?> clazz) throws Exception {
        //处理接口
        for (Class<?> interfaceClazz:clazz.getInterfaces()){
            if(Container.ioc.containsKey(interfaceClazz.getName())){
                throw new Exception("");
            }
            Container.ioc.put(interfaceClazz.getName(),clazz.newInstance());
        }
    }

    /**
     * 扫描所有类
     * @param path
     */
    private void doScanner(String path) {
        System.out.println(this.getClass().getClassLoader().getResource("/" + path.replaceAll("\\.","/")));
        //获取待扫描路径
        String filePath = this.getClass().getClassLoader().getResource("/" + path.replaceAll("\\.","/")).getFile();
        //遍历目录、加载目标类
        File root = new File(filePath);
        if(root!=null){
            for (File file:root.listFiles()){
                if(file.isDirectory()){
                    doScanner(path + Constant.DOT + file.getName());
                }else{
                    if(!file.getName().endsWith(Constant.CLASS_POSTFIX)) continue;
                    Container.classNames.add(path + Constant.DOT + file.getName().replace(Constant.CLASS_POSTFIX,""));
                }
            }
        }
    }
    /**
     * 加载配置文件
     * @param contextConfigLocation  配置文件路径
     */
    private void doLoadConfig(String contextConfigLocation) {
        //读取配置文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            PropertiesFactory.getInstance().load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
